﻿using Kairos.Properties;
using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;

namespace Kairos.Controllers
{
    [AttributeUsage(AttributeTargets.Method,Inherited=false,AllowMultiple=false)]
    public sealed class AccessControlAttribute : AuthorizeAttribute
    {
        public Roles Mandatory { get; private set; }

        public AccessControlAttribute(Roles roles)
        {
            this.Mandatory = roles;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (filterContext.HttpContext.User.IsInAnyRole(Mandatory))
            {
                Func<Roles, bool> shouldDiplsayUI = (mandatory) =>
                    {
                        return filterContext.HttpContext.User.IsInAnyRole(mandatory);
                    };

                filterContext.Controller.ViewBag.ShouldDisplayUI = shouldDiplsayUI;

                return;
            }

            // 403 Forbidden
            //
            // The server understood the request, but is refusing to fulfill it. 
            // Authorization will not help and the request SHOULD NOT be repeated. 

            filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
        }
    }
}